import { reactive } from "vue";
import { getById } from "@/api/recipe";
import {
  add,
  deleteByRecipeIds as deleteCollectionByRecipeIds,
} from "@/api/collect";
import { ElNotification } from "element-plus";

const uploadServerUrl = `${import.meta.env.VITE_API_SERVER}`;

export const _$ = reactive({
  state: {
    previewDialogVisible: false,
    dialogImageUrl: "",
  },
  requestParam: {
    id: null,
  },
  fileList: [],
  responseParam: {},
  separatedIngredients: [],
  separatedSteps: [],
});

export const $ = {
  loadDetail() {
    getById(_$.requestParam.id).then((data) => {
      _$.responseParam = data;
      const originalString = _$.responseParam.content;
      const ingredientsArray = originalString.split("\t");
      _$.separatedIngredients = ingredientsArray.map((item) => {
        if (item && item.trim) {
          // 使用正则表达式匹配数字作为分隔符
          const [key, value] = item.split(/(\d+)/).filter(Boolean);
          return {
            key: key ? key.trim() : "",
            value: value ? value.trim() : "",
          };
        }
        return { key: "", value: "" }; // 处理无效数据
      });

      const originalString2 = _$.responseParam.text;

      // 使用正则表达式将字符串拆分成步骤和内容
      const stepsArray = originalString2.split(/(?=步骤\d+)/);
      _$.separatedSteps = stepsArray.map((item) => {
        const stepRegex = /步骤(\d+)\s(.+)/;
        const match = item.match(stepRegex);
        if (match) {
          return { key: `步骤${match[1]}`, value: match[2] };
        }
        return { key: "", value: "" }; // 处理无效数据
      });

      _$.responseParam.images.split(",").forEach((item) => {
        _$.fileList.push({
          url: `${uploadServerUrl}${item}?Authorization=Bearer ${localStorage.getItem(
            "ats-user-token"
          )}`,
        });
      });
    });
  },

  onPreview(uploadFile) {
    _$.state.dialogImageUrl = uploadFile.url;
    _$.state.previewDialogVisible = true;
  },

  onCollection(id, item) {
    add({
      recipeId: id,
    }).then((_) => {
      ElNotification({
        title: "通知",
        message: "收藏成功",
        type: "success",
      });
      item.isCollect = true;
    });
  },

  onCancelCollection(id, item) {
    deleteCollectionByRecipeIds({
      ids: id.toString(),
    }).then((_) => {
      ElNotification({
        title: "通知",
        message: "已取消收藏",
        type: "success",
      });
      item.isCollect = false;
    });
  },

  clean() {
    _$.responseParam = {};
    _$.fileList.length = 0;
  },
};

export const to = {};
